package com.jdjz.usewebviewjs;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.google.gson.Gson;
import com.jdjz.common.TransScanEntity;
import com.jdjz.common.JsDemoScanEntity ;

import com.jdjz.webviewjslib.WebViewJS2;
import com.jdjz.webviewjslib.modle.ModleConfig;
import com.jdjz.webviewjslib.modle.ResultScan;
import com.jdjz.webviewjslib.modle.entity.ScanEntity;
import com.jude.utils.JUtils;
import com.jude.utils.permission.PermissionNameList;
import com.jude.utils.permission.PermissionRequestCode;
import com.jude.utils.permission.PermissionsUtil;
import com.yzq.zxinglibrary.android.CaptureActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;


public class MainActivity extends AppCompatActivity {

    EditText tvUrl;
    Button btnWebview;
    Context mContext;
    Toolbar toolbar;
    private final static int REQUESTCODE = 11; // 返回的结果码

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
        initEvent();
    }

    private void initView() {
        tvUrl = findViewById(R.id.tv_url);
        toolbar = (Toolbar) this.findViewById(R.id.toolbar3);


        btnWebview = findViewById(R.id.btn_webview);
    }

    private void initData() {
        mContext = this;
        toolbar.setTitle("知之JSSDK");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        toolbar.setOnMenuItemClickListener(onMenuItemClick);
    }
    private void initEvent() {
        EventBus.getDefault().register(this);
        //EventBus.getDefault().register(this);
        btnWebview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("tchl", "************");
                openWebView(tvUrl.getText().toString());
            }
        });

    }

    private void openWebView(String url) {
        Intent intent1 = new Intent(mContext, WebViewJS2.class);
        //JUtils.Log(tvUrl.getText().toString());
        intent1.putExtra("url", url); //url链接
        intent1.putExtra("title", "I'm title"); //toolbar 的title
        intent1.putExtra("isShowScreenSwitch", false); //isShowScreenSwitch: true显示横竖屏切换按钮，反之不显示
        intent1.putExtra("isShowToolbar", true);  //toolbar 是否显示， true显示，否则不显示
        intent1.putExtra("suposToken", "8d948d53f60e652fa17fd824c5a12d3a");  //supostoken
        intent1.putExtra("userName", "wenshun");//用户的登录名
        intent1.putExtra("isSuposUrl", "true");//链接是否来自supos。true是，false不是
        startActivity(intent1);
    }

    private Toolbar.OnMenuItemClickListener onMenuItemClick = new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            String msg = "";
            int id = menuItem.getItemId();
            if (id == R.id.scan) {
                // handleScreenSwitch(null);


                checkPermission1((Activity) mContext, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1024);

            }
            return true;
        }
    };

   private void handleScan(){
       JUtils.Log("scan");
       Intent intent = new Intent(mContext, CaptureActivity.class);
       intent.putExtra("isJSDemo",false);
       //startActivityForResult(intent, REQUESTCODE);
       startActivity(intent);
   }
    private void checkPermission1(Activity activity, @NonNull String[] permissions, @NonNull int reqCode) {
        //Build.VERSION_CODES.M

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            switch (reqCode) {

                case 1004:
                    handleScan();
                    break;
                default:
                    break;
            }
        } else {
            if (PermissionsUtil.hasPermission(mContext, permissions)) {
                JUtils.Log("checkPermission: have the permission");
                switch (reqCode) {

                    case 1024:
                        handleScan();
                        break;
                    default:
                        break;

                }
            } else {

                ActivityCompat.requestPermissions((Activity) mContext, permissions, reqCode);
                JUtils.Log("have no permissions");
            }
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        JUtils.Log("onRequestPermissionsResult:" + requestCode);
        for(int i=0;i<permissions.length;i++){
            JUtils.Log("permission name:"+permissions[i]+"  grantResults:"+grantResults[i]);
        }

        JUtils.Log("PermissionsUtil.isGranted:"+ PermissionsUtil.isGranted(grantResults)+"  "+ PermissionsUtil.hasPermission(this, permissions));

        if (requestCode == 1024 && PermissionsUtil.isGranted(grantResults)
                && PermissionsUtil.hasPermission(this, permissions)) {
            //EventBus.getDefault().post(new ScanEvent());
            handleScan();
            JUtils.Log("可以扫描二维码了");
        }
        else {
            JUtils.Toast(this.getString(com.jdjz.webviewjslib.R.string.permissontip));
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.menu_mainactivity, menu);
        return super.onCreateOptionsMenu(menu);
    }

    // 为了获取结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // RESULT_OK，判断另外一个activity已经结束数据输入功能，Standard activity result:
        // operation succeeded. 默认值是-1
        if (resultCode ==RESULT_OK) {
            if (requestCode == REQUESTCODE) {
                //int three = data.getIntExtra("three", 0);
                //设置结果显示框的显示数值
                //result.setText(String.valueOf(three));
                openWebView(data.getStringExtra("codedContent"));
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(JsDemoScanEntity transScanEntity) {
        ResultScan resultScan = new ResultScan();
        ScanEntity scanEntity = new ScanEntity();
        if (transScanEntity == null) {
            resultScan.setResponseCode(ModleConfig.RES404);
            resultScan.setResponseMsg("Scan:" + ModleConfig.RES_FAIL);
            resultScan.setResponseResult(null);
            String str2 = new Gson().toJson(resultScan);
            //callBackFunction.onCallBack(str2);

            JUtils.ToastLong(str2);

        } else {
            if (transScanEntity.isSuccess()) {
                resultScan.setResponseCode(ModleConfig.RES200);
                resultScan.setResponseMsg(ModleConfig.RES_SUCCESS);

                scanEntity.setCode(transScanEntity.getResult());

                resultScan.setResponseResult(scanEntity);
                String str2 = new Gson().toJson(resultScan);
                JUtils.ToastLong(str2);
                JUtils.Log(transScanEntity.getResult());
                openWebView(transScanEntity.getResult());

            } else {
                resultScan.setResponseCode(ModleConfig.RES404);
                resultScan.setResponseMsg(transScanEntity.getResult());

                resultScan.setResponseResult(scanEntity);
                String str2 = new Gson().toJson(resultScan);
                JUtils.ToastLong(str2);
            }
        }
    }
}
